package com.hust.controller;

import com.hust.domain.User;
import com.hust.service.LoginAndRegisterService;
import com.hust.util.EncodeUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
public class LoginAndRegisterController {

    @Autowired
    LoginAndRegisterService loginAndRegisterService;

    @Autowired
    EncodeUtil encodeUtil;

    @RequestMapping("/loginverify")
    @ResponseBody
    public boolean loginVerify(String username, String password, HttpServletRequest request) {

        User user = loginAndRegisterService.searchUserByuName(username);
        if (user != null) {
            String md5pass = encodeUtil.MD5Util(password);
            if (md5pass.equals(user.getuPwd())) {
                HttpSession session = request.getSession();
                System.out.println(session);
                request.getSession().setAttribute("user",user);
                return true;
            } else {
                return false;
            }
        }
        return false;

        /*
        Subject subject = SecurityUtils.getSubject();
        //封装用户登录数据
        UsernamePasswordToken token =new UsernamePasswordToken(username,password);

        try{
            subject.login(token);
            return true;
        }catch (UnknownAccountException e){//用户名不存在
            model.addAttribute("user",null);
            return false;
        }catch (IncorrectCredentialsException e){
            model.addAttribute("user",null);
            return false;
        }*/
    }

    @RequestMapping("/register")
    public String register() {
        return "register";
    }

    @RequestMapping("/userregister")
    @ResponseBody
    public boolean userRegister(String username, String password) {
        User user = new User();
        user.setuName(username);
        String md5password = encodeUtil.MD5Util(password);
        user.setuPwd(md5password);
        user.setuType("0");
        int flag = loginAndRegisterService.insertUser(user);
        if (flag != -1) {
            return true;
        } else {
            return false;
        }
    }
    @RequestMapping("/logout")
    public String userLogout( HttpServletRequest request) {
     HttpSession session=  request.getSession();
     session.removeAttribute("user");
     return "login";
    }

}